﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RclSystem
{
    public partial class SalemanStatement : UIPage
    {
        List<StatementAccountVo> sortedVolist = new List<StatementAccountVo>();
        //记录业务员汇总信息
        Dictionary<string, StatementAccountVo> hashTable = new Dictionary<string, StatementAccountVo>();
        public SalemanStatement()
        {
            InitializeComponent();
        }

        private void queryAccounts()
        {
            sortedVolist = new List<StatementAccountVo>();
            hashTable = new Dictionary<string, StatementAccountVo>();
            uiDataGridView1.Rows.Clear();
            List<StatementAccountVo> volist = new List<StatementAccountVo>();
            DataTable dt_deliver = new DataTable();
            DataTable dt_receipt = new DataTable();
            DataTable dt_saleman = new DataTable();
            DataTable dt_company = new DataTable();
            if (txt_saleman.Text.Trim() == "")
            {
                //获取所有业务员列表
                dt_saleman = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_saleman order by id");
            }
            else
            {
                //获取指定业务员
                dt_saleman = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_saleman where name = '" + txt_saleman.Text.Trim() + "'");
            }
            if(dt_saleman.Rows.Count > 0)
            {
                foreach (DataRow row in dt_saleman.Rows)
                {
                    Dictionary<string, bool> hashCompany = new Dictionary<string, bool>();//记录单位期初数是否被累加
                    //获取指定业务员发货单列表
                    dt_deliver = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_delivery where salesman = '" + row["name"].ToString() + "' and deliverdate >= '" + dt_qstart.Value.ToString("yyyy-MM-dd")
                    + "' and deliverdate <= '" + dt_qend.Value.ToString("yyyy-MM-dd") + "' order by deliverdate");

                    if (dt_deliver.Rows.Count > 0)
                    {
                        foreach (DataRow drow in dt_deliver.Rows)
                        {                            
                            if (hashTable.ContainsKey(drow["salesman"].ToString()))
                            {
                                StatementAccountVo vo = hashTable[drow["salesman"].ToString()];
                                vo.count += double.Parse(drow["salecount"].ToString());
                                vo.deliverprice += double.Parse(drow["saleamount"].ToString());
                                vo.balance += double.Parse(drow["saleamount"].ToString());                                
                                hashTable[drow["salesman"].ToString()] = vo;
                            }
                            else
                            {
                                StatementAccountVo vo = new StatementAccountVo();
                                vo.companyname = drow["salesman"].ToString();//这里用companyname来保存业务员姓名
                                vo.count = double.Parse(drow["salecount"].ToString());
                                vo.deliverprice = double.Parse(drow["saleamount"].ToString());
                                vo.balance = double.Parse(drow["saleamount"].ToString());
                                hashTable.Add(drow["salesman"].ToString(), vo);
                            }
                        }
                    }
                    //获取业务员的收款单据列表
                    dt_receipt = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_receipt where salesman = '" + row["name"].ToString() + "' and  receiptdate >= '" + dt_qstart.Value.ToString("yyyy-MM-dd")
                        + "' and receiptdate <= '" + dt_qend.Value.ToString("yyyy-MM-dd") + "'" );

                    if (dt_receipt.Rows.Count > 0)
                    {
                        foreach (DataRow prow in dt_receipt.Rows)
                        {
                            if (hashTable.ContainsKey(prow["salesman"].ToString()))
                            {
                                StatementAccountVo vo = hashTable[prow["salesman"].ToString()];
                                vo.receiptprice += double.Parse(prow["receiptamount"].ToString());                                
                                //如果收款单关联期初数，收款金额也需要累加
                                if(prow["parentid"].ToString() == "0")
                                {
                                    vo.deliverprice += double.Parse(prow["receiptamount"].ToString());
                                }
                                else
                                {
                                    vo.balance -= double.Parse(prow["receiptamount"].ToString());
                                }
                                hashTable[prow["salesman"].ToString()] = vo;
                            }
                            else
                            {
                                StatementAccountVo vo = new StatementAccountVo();
                                vo.companyname = prow["salesman"].ToString();
                                vo.receiptprice = double.Parse(prow["receiptamount"].ToString());
                                //如果收款单关联期初数，收款金额也需要累加
                                if (prow["parentid"].ToString() == "0")
                                {
                                    vo.deliverprice += double.Parse(prow["receiptamount"].ToString());
                                }
                                else
                                {
                                    vo.balance -= double.Parse(prow["receiptamount"].ToString());
                                }
                                hashTable.Add(prow["salesman"].ToString(), vo);
                            }
                        }
                    }
                    //查询单位期初数是否已累加
                    //查询业务员所有关联单位
                    dt_company = MySQLHelper.ExecuteQuery("SELECT * FROM tbl_company where parentid = " + row["id"].ToString());
                    if (dt_company.Rows.Count > 0)
                    {
                        foreach (DataRow crow in dt_company.Rows)
                        {
                            if(Math.Round(double.Parse(crow["initalamount"].ToString()), 2) == 0)
                            {
                                //如果单位期初数为0,不做累计
                                continue;
                            }
                            if (hashTable.ContainsKey(row["name"].ToString()))
                            {
                                StatementAccountVo vo = hashTable[row["name"].ToString()];
                                //累加应收款金额
                                vo.deliverprice += double.Parse(crow["initalamount"].ToString());
                                vo.balance += double.Parse(crow["initalamount"].ToString());
                                hashTable[row["name"].ToString()] = vo;
                            }
                            else
                            {
                                StatementAccountVo vo = new StatementAccountVo();
                                vo.companyname = row["name"].ToString();//这里用companyname来保存业务员姓名
                                vo.deliverprice = double.Parse(crow["initalamount"].ToString());
                                vo.balance = double.Parse(crow["initalamount"].ToString());
                                hashTable.Add(row["name"].ToString(), vo);
                            }
                                
                        }
                    }
                }
            }
            double count_total = 0;
            double deliverprice_total = 0;
            double receiptprice_total = 0;
            double balance_total = 0;
            int index = 0;
            //显示
            foreach (KeyValuePair<string, StatementAccountVo> kvp in hashTable)
            {
                index = this.uiDataGridView1.Rows.Add();
                this.uiDataGridView1.Rows[index].Cells[0].Value = index + 1;
                this.uiDataGridView1.Rows[index].Cells[1].Value = kvp.Value.companyname;
                this.uiDataGridView1.Rows[index].Cells[2].Value = kvp.Value.count;
                this.uiDataGridView1.Rows[index].Cells[3].Value = kvp.Value.deliverprice.ToString();
                this.uiDataGridView1.Rows[index].Cells[4].Value = kvp.Value.receiptprice.ToString();
                this.uiDataGridView1.Rows[index].Cells[5].Value = Math.Round(kvp.Value.balance, 2).ToString();

                count_total += kvp.Value.count;
                deliverprice_total += kvp.Value.deliverprice;
                receiptprice_total += kvp.Value.receiptprice;
                balance_total += kvp.Value.balance;
            }
            //生产合计行
            index = this.uiDataGridView1.Rows.Add();
            this.uiDataGridView1.Rows[index].Cells[0].Value = index + 1;
            this.uiDataGridView1.Rows[index].Cells[1].Value = "合计";
            this.uiDataGridView1.Rows[index].Cells[2].Value = Math.Round(count_total, 3).ToString();
            this.uiDataGridView1.Rows[index].Cells[3].Value = Math.Round(deliverprice_total, 2).ToString();
            this.uiDataGridView1.Rows[index].Cells[4].Value = Math.Round(receiptprice_total, 2).ToString();
            this.uiDataGridView1.Rows[index].Cells[5].Value = Math.Round(balance_total, 2).ToString();

        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            queryAccounts();
        }

        private void SalemanStatement_Initialize(object sender, EventArgs e)
        {
            dt_qend.Value = DateTime.Now;
            dt_qstart.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        }

        private void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (uiDataGridView1.Columns[e.ColumnIndex].Name == "btn_detail" && e.RowIndex >= 0)
            {
                if(uiDataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue.ToString() == "合计")
                {
                    return;
                }
                DataGridViewRow vr = uiDataGridView1.Rows[e.RowIndex];
                string salesman = vr.Cells[1].Value.ToString();
                double total = double.Parse(vr.Cells[5].Value.ToString());
                //明细对话框
                SaleStatementDetail sdetail = new SaleStatementDetail(salesman, dt_qstart.Value.ToString("yyyy-MM-dd"), dt_qend.Value.ToString("yyyy-MM-dd"));
                sdetail.ShowDialog();
            }
        }

        private void uiDataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if(e.ColumnIndex > -1 && e.RowIndex > -1)
            {
                // 检查是否是按钮列
                if (uiDataGridView1.Columns[e.ColumnIndex].Name == "btn_detail")
                {
                    if(e.ColumnIndex == 6 && uiDataGridView1.Rows[e.RowIndex].Cells[1].FormattedValue.ToString() == "合计")
                    {
                        // 跳过绘制按钮
                        e.Handled = true;
                    }
                }
            }
            
        }
    }
}
